#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re, sys
import Image, eParser
import getopt
from blog import blog
from photo import photo
from getpass import getpass
from photo import photo
import gtk



#------- CONSTANTS $ GLOBAL VARS ------

POST = """__________________________

<div class="separator" style="clear: both; text-align: center;">
<a href="%bigimg%" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="320" src="%bigimg%" width="226" /></a></div>

<b>%name%</b>

%description%


<b>%price% euros</b>.
<a href="javascript:;" onclick="simpleCart.add('name=%name%','price=%price%','image=%urlimagecart%');return false;"><img border="0" src="http://lh6.ggpht.com/_y2eqa6Fym0I/S3dng9prPXI/AAAAAAAACsY/ancuLwiGfLk/carro.jpg" /></a>

<div style="text-align: right;">
Código: %code%</div>"""

CELL = """<td><a href="%bigimg%" rel="lightbox"><img alt="%name%" height="100" width="100" border="0" src="%smallimg%" /></a><br>
Precio: €%price%<br>
Nombre : %name%<br>
<a href="%urlblog%">Más info</a><br>
<a href="javascript:;" onclick="simpleCart.add('name=%name%','price=%price%','image=%miniimg%');return false;">Añadir al carro</a><br>"""

LOGIN = {"user":None, "password":None}
VERBOSE = False
PRODUCT = {}
SERVICES = {}
BLOGS = {}
PAGES = {}

# ===== CLASSES ===== 
class Window:
  
  def __init__(self):
    self.builder = gtk.Builder()
    self.builder.add_from_file('ui/ui.glade')
    #Build Login
    self.login = self.builder.get_object('login')
    #Build AddWindow
    self.addwindow = self.builder.get_object('addproduct')
    #Build Alert
    self.alert = self.builder.get_object('alert')
    #Build Selector
    self.blogselector = self.builder.get_object('blogselector')
    #Build Entries
    self.entryuser = self.builder.get_object("user")
    if LOGIN['user']:
      self.entryuser.set_text(LOGIN['user'])
    self.entrypasswd = self.builder.get_object("passwd")
    self.name = self.builder.get_object("name")
    self.code = self.builder.get_object("code")
    self.price = self.builder.get_object("price")
    self.bigimg = self.builder.get_object("bigimg")
    self.smallimg = self.builder.get_object("smallimg")
    self.description = self.builder.get_object("description")
    self.bloglist = self.builder.get_object("bloglist")
    self.pagelist = self.builder.get_object("pagelist")
    self.comboblog = self.builder.get_object("comboblog")
    self.combopages = self.builder.get_object("combopages")
    
    self.login.show_all()
    self.builder.connect_signals(self)
    
  def on_accept_clicked(self, widget):
    if not LOGIN['user']:
      LOGIN['user'] = self.entryuser.get_text()
    LOGIN['password'] = self.entrypasswd.get_text()
    self.login.hide()
    
    #Initialize Services
    if VERBOSE:
      print "Initializing services...",
    try:
      SERVICES['blog'] = blog(LOGIN['user'], LOGIN['password'])
    except:
      self.alert.show()
    SERVICES['photo'] = photo(LOGIN['user'], LOGIN['password'])
    if VERBOSE:
      print "OK"
      
    if VERBOSE:
      print "Searching blogs...",
    blogs = SERVICES['blog'].ListBlogs()
    if VERBOSE:
      print "OK"

    for b in blogs:
      self.bloglist.append(b.title.text)
      BLOGS[b.title.text] = blog.GetSelfLink().href.split("/")[-1]
    
    self.blogselector.run()
    self.addwindow.run()
    sys.exit(0)
    
  def on_add_clicked(self, widget):
    PRODUCT["name"] = self.name.get_text()
    PRODUCT["price"] = self.price.get_text()
    PRODUCT["code"] = self.code.get_text()
    PRODUCT["bigimg"] = self.bigimg.get_filename()
    PRODUCT["smallimg"] = self.smallimg.get_filename()
    PRODUCT["description"] = self.description.get_text(self.description.get_start_iter(),
                                                       self.description.get_end_iter())
    self.addwindow.hide()
    main()
    sys.exit(0)
    
  def on_comboblog_changed(self, widget):
    model = box.get_model()
    index = box.get_active()
    if index and VERBOSE:
      print  model[index][0], 'selected'
    
    if VERBOSE:
      print "Searching blog pages..."
    pages = SERVICES['blog'].ListPages(model[index][0])
    if VERBOSE:
      print "OK"
    
    for page in pages:
      self.pagelist.append(page.title.text)
      PAGES[page.title.text] = page
      
  def on_combopage_changed(self,widget):
    
    
        
  def gtk_main_quit(self,widget):
    sys.exit(0)

# ===== FUNCTIONS ===== 

def resize(imageFile):
  im1 = Image.open(imageFile)
  im1 = im1.resize((50, 50), Image.BICUBIC)
  im1.save("/tmp/miniImage.jpg")
  return "/tmp/miniImage.jpg"
  
def usage():
  print "eboutique [-v] [-h] [--help] [-u] [--user]"
  
def getOptions():
  try:
    opts, args = getopt.getopt(sys.argv[1:], "hu:v", ["help", "user="])
  except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)
  for o, a in opts:
    if o == "-v":
      VERBOSE = True
    elif o in ("-h", "--help"):
      usage()
      sys.exit(0)
    elif o in ("-u", "--user"):
      LOGIN['user'] = a
    else:
      assert False, "unhandled option"
  
def main():

  for i in range(0,len(pages)):
    print i,"-",pages[i].title.text
  
  print "Select product type: ",
  page = int(raw_input())
                
  PRODUCT["bigimg"] = SERVICES['photo'].PostPhoto(PRODUCT["bigimg"])
  PRODUCT["miniimg"] = SERVICES['photo'].PostPhoto(resize(PRODUCT["smallimg"]))
  PRODUCT["smallimg"] = SERVICES['photo'].PostPhoto(PRODUCT["smallimg"])
  SERVICES['blog'].CreatePost(blog_id, PRODUCT["name"], eParser.ParseTemplate(POST, PRODUCT))
  PRODUCT["urlblog"] = SERVICES['blog'].getPostURL(blog_id, PRODUCT['name'])

  print PRODUCT

  html = pages[page].content.text
  
  table = eParser.getTables(html)[0]
  
  if len(table[len(table)-1]) < 3:
    table[len(table)-1].append(eParser.ParseTemplate(CELL, PRODUCT))
  else:
    row = [eParser.ParseTemplate(CELL, PRODUCT)]
    table.append(row)
    
  html = "<center>\n" + eParser.TableToHTML(table) + "\n</center>"
  
  SERVICES['blog'].UpdateEntry(pages[page], "content", html)
    
      

  
# ---- MAIN -------------------------------------
if __name__ == "__main__":  
  getOptions()
  l = Window()
  gtk.main()
